/**
 * @Title: UploadToTempSyncLogic.java
 * @Package: com.jason.fingerprint.logic
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月24日 上午10:42:21
 * @Version: V1.0
 */
package com.jason.fingerprint.logic;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import org.kymjs.aframe.http.HttpCallBack;
import org.kymjs.aframe.http.KJFileParams;
import org.kymjs.aframe.http.KJHttp;
import org.kymjs.aframe.utils.StringUtils;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.gson.GsonBuilder;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.AppGlobal;
import com.jason.fingerprint.beans.BaseBean;
import com.jason.fingerprint.beans.WorkVisitBean;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.common.DateFormat;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.configs.DataConfig;
import com.jason.fingerprint.configs.HttpConfig;
import com.jason.fingerprint.utils.CodecUtils;
import com.jason.fingerprint.utils.DataUtils;

/**
 * @ClassName: UploadToTempSyncLogic
 * @Description: 资源上传
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月24日 上午10:42:21
 */
public class UploadToTempSyncLogic extends Logic {

	private static final String TAG = "UploadToTempSyncLogic";

	private Handler mHandler;
	private boolean mIsCallBack = false;// 是否有回调，此需要Handle,默认不回调
	private Message mMessage;
	private int mServiceId;
	private List<ImageOrAudioBean> mImageOrAudioBeans = new ArrayList<ImageOrAudioBean>();
	private int mSize = -1;// 总共要上传的条数
	private int mIndex = 0;// 上传到第几条

	private String mSponsorType; // 活动类型（0-集中教育 1-集中劳动 2-个别教育 3-个别劳动）
//	private String mSponsorId; // 活动ID(集中劳动、集中教育)
	
	public UploadToTempSyncLogic() {

	}

	public UploadToTempSyncLogic(AppContext appContext, Handler handler) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
	}

	public UploadToTempSyncLogic(AppContext appContext, Handler handler,
			boolean isCallBack) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
		this.mIsCallBack = isCallBack;
	}

	public UploadToTempSyncLogic(AppContext appContext, Handler handler,
			boolean isCallBack, int serviceId) {
		super(appContext);
		this.mHandler = handler;
		this.mMessage = new Message();
		this.mIsCallBack = isCallBack;
		this.mServiceId = serviceId;
	}

//	public UploadToTempSyncLogic(AppContext appContext, Handler handler,
//			boolean isCallBack, int serviceId, String sponsorType, String sponsorId) {
//		this(appContext, handler, isCallBack, serviceId);
//		this.mSponsorType = sponsorType;
//		this.mSponsorId = sponsorId;
//	}
	
	public UploadToTempSyncLogic(AppContext appContext, Handler handler,
			boolean isCallBack, String sponsorType) {
		this(appContext, handler, isCallBack, 0);
		this.mSponsorType = sponsorType;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jason.fingerprint.logic.Logic#execute()
	 */
	@Override
	public void execute() {
		// TODO Auto-generated method stub
		StringBuilder where = new StringBuilder();
		if (!StringUtils.isEmpty(mSponsorType)) {
			if (mSponsorType.equals(DataConfig.REGISTER_TYPE_2)
					|| mSponsorType.equals(DataConfig.REGISTER_TYPE_3)) {
				mServiceId = 2;
			}else {
				mServiceId = 3;
			}
			where.append("sponsorType = '");
			where.append(mSponsorType);
//			if (mSponsorId != null) {
//				where.append("' and sponsorId = '");
//				where.append(mSponsorId);
//			} 
			where.append("'");
		} else {
			where.append("serviceId = ");
			where.append(mServiceId);
		}
		where.append(" and state = 1");
		Log.i(TAG, "---execute--where:" + where.toString());
		mImageOrAudioBeans = mKjdb.findAllByWhere(ImageOrAudioBean.class,
				where.toString());
		mSize = -1;
		mIndex = 0;
		if (mImageOrAudioBeans != null && !mImageOrAudioBeans.isEmpty()) {
			mSize = mImageOrAudioBeans.size();
			uploadSource();
		} else {
			mMessage.what = UIHelper.FILE_UPLOAD_SUCCESS;
			send();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.jason.fingerprint.logic.Logic#send()
	 */
	@Override
	public void send() {
		// TODO Auto-generated method stub
		if (mIsCallBack) {
			mHandler.sendMessage(mMessage);
			mMessage = new Message();
		}
	}

	// 上传资源
	private void uploadSource() {
		if (mIndex >= mSize) {
			mMessage.what = UIHelper.FILE_UPLOAD_SUCCESS;
			send();
			return;
		}
		final ImageOrAudioBean audioBean = mImageOrAudioBeans.get(mIndex);
		if (audioBean == null) {
			mIndex ++ ;
			uploadSource();
			return;
		}
		mParams = new KJFileParams();
		mParams.put(AppGlobal.HTTP_PARAM_IMEI, mImei);
		mParams.put("serviceId", String.valueOf(mServiceId));
		String fileName = audioBean.getFileName();
		if (audioBean.getFileType() == 1) {
			fileName += ".jpg";
		}else {
			fileName += ".amr";
		}
		mParams.put("fileInputFileName", fileName);
		mParams.put("type", String.valueOf(audioBean.getFileType() == 1 ? 0 : 1));
		try {
			File file = new File(audioBean.getFilePath());
			FileInputStream stream = new FileInputStream(file);
			mParams.put("fileInput", stream, fileName);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		if (mServiceId == 1) {
			// (单文件上传)新增日常报到的记录。
			mParams.put("rymcId", audioBean.getParentId());
			mParams.put("startTime", DataUtils.converDatLongToString(
					audioBean.getCreateDate(), DateFormat.DATE_YMD_HMS));
			mParams.put("endTime", DataUtils.converDatLongToString(
					audioBean.getUploadDate(), DateFormat.DATE_YMD_HMS));
		} else if (mServiceId == 2) {
			// (多文件上传)上传 照片、录音 （个别活动）-----(多文件上传)新增个别教育、个别劳动签到记录时用到的照片
			mParams.put("eduComId", audioBean.getSponsorId());
		} else if (mServiceId == 3) {
			// (多文件上传)-----(多文件上传)上传 照片、录音 （集中活动）
			mParams.put("sponsorId", audioBean.getSponsorId());
		} else if (mServiceId == 4) {
			// (多文件上传)（新增走访记录）将走访的签到记录上传到平台。
			String parenId = audioBean.getParentId();
			WorkVisitBean visitBean = mKjdb.findById(parenId,
					WorkVisitBean.class);
			if (visitBean != null) {
				if (visitBean.getWorkId() != 0) {
					mParams.put("id", audioBean.getParentId());
				} else {
					mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
					send();
					return;
				}
			} else {
				mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
				send();
				return;
			}

		} else if (mServiceId == 5) {
			// (单文件上传)外出请假（记录上传）上传图片----(单文件上传)外出请假（记录上传）上传图片
			mParams.put("signTyp", audioBean.getSignType());
			mParams.put("id", audioBean.getParentId());
		}
		String url = HttpConfig.POST_URL_FILEUPLOAD_UPLOADTOTEMP;
		Log.i(TAG, "----->API:" + url);
		Log.i(TAG, "----->mParams:" + mParams.getParamString());
		KJHttp kjHttp = new KJHttp();
		kjHttp.post(url, mParams, new HttpCallBack() {

			@Override
			public void onSuccess(Object arg0) {
				Log.i(TAG, "----->arg0:" + arg0.toString());
				String result = null;
				try {
					result = CodecUtils.base64Decode(arg0.toString());
				} catch (Exception e) {
					mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
					send();
					return;
				}
				Log.i(TAG, "----->Result:" + result);
				BaseBean bean = new GsonBuilder().create().fromJson(result,
						BaseBean.class);
				if (bean != null && bean.isSuccess()) {
					audioBean.setState(2);
					mKjdb.update(audioBean);
					mIndex++;
					uploadSource();
				} else {
					mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
					send();
				}
			}

			@Override
			public void onLoading(long arg0, long arg1) {
				Log.i(TAG, "----->Result:arg0:" + arg0 + ",arg1:" + arg1);
			}

			@Override
			public void onFailure(Throwable arg0, int arg1, String arg2) {
				Log.i(TAG, "----->Result:arg1:" + arg1 + ",arg2:" + arg2);
				mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
				send();
			}
		});

	}

	/* (non-Javadoc)
	 * @see com.jason.fingerprint.logic.Logic#destory()
	 */
	@Override
	public void destory() {
		// TODO Auto-generated method stub
		
	}

}
